package com.snowy.hidden.user.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snowy.hidden.user.domain.model.SysRelation;
import com.snowy.hidden.user.domain.model.SysRole;
import com.snowy.hidden.user.domain.model.SysUser;
import com.snowy.hidden.user.domain.req.UserListByRoleListReq;
import com.snowy.hidden.user.mapper.SysRelationMapper;
import com.snowy.hidden.user.mapper.SysRoleMapper;
import com.snowy.hidden.user.mapper.SysUserMapper;
import com.snowy.hidden.user.service.SysRoleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色(SysRole)表服务实现类
 *
 * @author makejava
 * @since 2023-11-30 00:27:43
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {


    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysRelationMapper sysRelationMapper;

    @Override
    public List<String> listUserRoleCode(String userId) {
        if(StrUtil.isBlank(userId)){
            return CollectionUtil.newArrayList();
        }
        List<SysRole> sysRoleList = this.baseMapper.listByUserId(userId);
        return sysRoleList.stream().map(item->{
            return item.getCode();
        }).collect(Collectors.toList());
    }

    @Override
    public List<SysUser> getUserListByRoleCodeList(UserListByRoleListReq userListByRoleListReq) {
        //1、获取角色id集合
        List<String> roleCodeList = userListByRoleListReq.getRoleCodeList();
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(SysRole::getCode, roleCodeList);
        List<SysRole> sysRoleList = this.list(lambdaQueryWrapper);
        List<String> roleIdList = sysRoleList.stream().map(SysRole::getId).collect(Collectors.toList());



        LambdaQueryWrapper<SysRelation> lambdaQueryWrapperSysRelation = new LambdaQueryWrapper<>();
        lambdaQueryWrapperSysRelation.in(SysRelation::getTargetId, roleIdList);
        lambdaQueryWrapperSysRelation.eq(SysRelation::getCategory, "SYS_USER_HAS_ROLE");
        List<String> useList=sysRelationMapper.selectList(lambdaQueryWrapperSysRelation).stream()
                .map(SysRelation::getObjectId).collect(Collectors.toList());
        if (useList.isEmpty()){
            return Collections.emptyList();
        }
        LambdaQueryWrapper<SysUser> lambdaQueryWrapperSysUser = new LambdaQueryWrapper<>();
        lambdaQueryWrapperSysUser.in(SysUser::getId, useList);
        return this.sysUserMapper.selectList(lambdaQueryWrapperSysUser);

    }




}
